package ca.badenhorst.ourtrition.activity;

import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.io.File;

import ca.badenhorst.ourtrition.R;
import ca.badenhorst.ourtrition.db.DatabaseHelper;
import ca.badenhorst.ourtrition.model.FoodGroup;
import ca.badenhorst.ourtrition.service.CopyDBService;


public class FoodGroupActivity extends Activity implements AdapterView.OnItemClickListener {
    public static final String DB_COPIED =
            "ca.badenhorst.intent.action.DATABASE_COPIED";
    public static final String RESULT = "result";
    public static final String SUCCESS = "success";
    public static final String FAILURE = "failure";

    LinearLayout progressBar;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_group);

        progressBar = (LinearLayout) findViewById(R.id.food_group_progress_bar);
        listView = (ListView) findViewById(R.id.food_group_list_view);
        listView.setOnItemClickListener(this);

        if (!doesDatabaseExist()) {
            refreshDatabase();
        } else {
           refreshFoodGroups();
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Cursor cursor = (Cursor) listView.getAdapter().getItem(position);
        String groupCode = cursor.getString(1);
        String groupDescription = cursor.getString(2);
        if (groupCode != null && !TextUtils.isEmpty(groupCode)) {
            Intent listFoodDesc = new Intent(FoodGroupActivity.this, ListFoodsActivity.class);
            listFoodDesc.putExtra(FoodGroup.GROUP_CODE, groupCode);
            listFoodDesc.putExtra(FoodGroup.DESCRIPTION, groupDescription);
            startActivity(listFoodDesc);
        }
    }

    private void refreshFoodGroups() {
        new GetFoodGroupListTask().execute();
    }

    CopyDBReceiver copyDBReceiver;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.food_group, menu);

        // Get the SearchView and set the searchable configuration
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.food_group_search_item).getActionView();
        // Assumes current activity is the searchable activity
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.refresh_database) {
            refreshDatabase();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void refreshDatabase() {
        if (connected()) {
            listView.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);

            deleteDatabase(DatabaseHelper.DATABASE_NAME);

            IntentFilter filter = new IntentFilter(DB_COPIED);
            copyDBReceiver = new CopyDBReceiver();
            registerReceiver(copyDBReceiver, filter);
            startService(new Intent(this, CopyDBService.class));
        } else {
            Toast.makeText(this, "please check your internet connection and try again", Toast.LENGTH_LONG);
        }

    }

    private boolean connected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED);
    }

    private boolean doesDatabaseExist() {
        File dbFile = getDatabasePath(DatabaseHelper.DATABASE_NAME);
        return dbFile.exists();
    }

    private class CopyDBReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            String result = extras.getString(FoodGroupActivity.RESULT);
            if (FoodGroupActivity.SUCCESS.equals(result)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(FoodGroupActivity.this, "new database loaded ", Toast.LENGTH_SHORT).show();
                    }
                });
                refreshFoodGroups();
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(FoodGroupActivity.this, "errors loading database", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            progressBar.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            context.unregisterReceiver(copyDBReceiver);
        }
    }

    private class GetFoodGroupListTask extends AsyncTask<Void, Void, Cursor> {

        public GetFoodGroupListTask() {
        }

        @Override
        protected Cursor doInBackground(Void... voids) {
            DatabaseHelper helper = new DatabaseHelper(FoodGroupActivity.this);
            SQLiteDatabase db = helper.getReadableDatabase();

            return db.rawQuery("select id as _id, "+FoodGroup.GROUP_CODE+","+FoodGroup.DESCRIPTION +" from food_groups order by "+FoodGroup.DESCRIPTION, new String[0]);
        }

        protected void onPostExecute(Cursor cursor) {
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(FoodGroupActivity.this, R.layout.list_item, cursor, new String[]{FoodGroup.DESCRIPTION}, new int[]{R.id.list_item}, 0);
            listView.setAdapter(adapter);
        }
    }
}
